package com.agent.membership.mapper;

import com.agent.membership.entity.MembershipSubscription;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 会员订阅Mapper
 * @author Jeff_Wan
 * @description 会员订阅数据库操作接口
 */
@Mapper
public interface MembershipSubscriptionMapper extends BaseMapper<MembershipSubscription> {

    /**
     * 查询用户有效订阅
     * @param userId 用户ID
     * @return 有效订阅信息
     */
    MembershipSubscription findActiveSubscription(@Param("userId") Long userId);

    /**
     * 查询即将过期订阅
     * @param tomorrow 到期时间(UTC)
     * @return 订阅列表
     */
    List<MembershipSubscription> findExpiringSubscriptions(
            @Param("tomorrow") LocalDate tomorrow);

    /**
     * 查询已过期订阅
     * @param yesterday 过期时间(UTC)
     * @return 订阅列表
     */
    List<MembershipSubscription> findExpiredSubscriptions(
            @Param("yesterday") LocalDate yesterday);

    /**
     * 根据用户ID查询会员订阅
     * @param userId 用户ID
     * @return 会员订阅
     */
    @Select("SELECT * FROM membership WHERE user_id = #{userId}")
    MembershipSubscription selectByUserId(@Param("userId") Long userId);

    @Update("UPDATE membership SET " +
            "plan_type = #{planType}, " +
            "subscription_type = #{subscriptionType}, " +
            "start_date = #{startDate}, " +
            "end_date = #{endDate}, " +
            "auto_renew = #{autoRenew}, " +
            "last_credit_issued_date = #{lastCreditIssuedDate} " +
            "WHERE user_id = #{userId}")
    int updateMembership(@Param("userId") Long userId,
                         @Param("planType") String planType,
                         @Param("subscriptionType") String subscriptionType,
                         @Param("startDate") LocalDateTime startDate,
                         @Param("endDate") LocalDateTime endDate,
                         @Param("autoRenew") Boolean autoRenew,
                         @Param("lastCreditIssuedDate") LocalDateTime lastCreditIssuedDate);

    /**
     * 查询有效会员订阅
     * @param today 当前日期(UTC)
     * @return 有效会员列表
     */
    @Select("SELECT * FROM membership WHERE end_date >= #{today} AND plan_type != 'FREE'")
    List<MembershipSubscription> findActiveMemberships(@Param("today") LocalDate today);
}